import { Button, Flex, Upload, UploadProps, message } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { useMessageApi } from '@/component/context/messageContext/message'
import settingApi from '../api'
import { useEffect } from 'react'
import { renderAsync } from 'docx-preview'
import './index.scss'
export default function LegalDocx() {
  const messageApi = useMessageApi()

  const uploadProps: UploadProps = {
    accept: '.docx',
    maxCount: 1,
    showUploadList: false,
    customRequest({ file }) {
      // 创建一个新的File对象，重命名为legal.docx
      const renamedFile = new File([file as unknown as File], 'legal.docx', {
        type: (file as unknown as File).type,
      })

      settingApi
        .uploadFile(renamedFile)
        .then((res) => {   
          messageApi.success('上传成功')
          setTimeout(() => {
            getDocx()
          }, 500);
        })
        .catch((err) => {
          messageApi.error('上传失败，请稍后再试')
        })
    },
  }

  const getDocx = async () => {
    let res = await settingApi.getDocxFile()
    let target = document.getElementById('panel-section')
    if (target) {
      renderAsync(res.data, target as HTMLElement).then((x) =>
        console.log('docx: finished')
      )
    } else {
      console.log('target is null')
    }
  }

  useEffect(() => {
    getDocx()
  }, [])

  return (
    <Flex vertical gap="1rem">
      <Flex justify="right">
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />}>更新法务文档</Button>
        </Upload>
      </Flex>
      <div className="docx" id="panel-section"></div>
    </Flex>
  )
}
